<?php
class RegisterController extends AppController {
    
    public $components = array('Recaptcha.Recaptcha');
    public $helpers = array('Recaptcha.Recaptcha');
    public $uses = array('User');
    
    protected function registerNewUserRequest() {
        $dbdate = Configure::read('Creativos.formats.dbdate');
        $tokendur = Configure::read('Creativos.register.token_duration');
        $tokendurspan = '+'.$tokendur['value'].' '.$tokendur['type'];
        
        App::uses('Utitlity','Security');
        
        $currdate = date_create("now");
        $expdate = date_create("now");
        date_modify($expdate, $tokendurspan);
        
        $this->request->data['User']['password'] = $this->Auth->password($this->request->data['User']['password']);
        $this->request->data['User']['role'] = 'USER';
        $this->request->data['User']['token_expired'] = date_format($expdate, $dbdate);
        $this->request->data['User']['token'] = String::uuid();
        $this->request->data['User']['regdate'] = date_format($currdate, $dbdate);
        $this->request->data['User']['lastactiv'] = date_format($currdate, $dbdate);
        
        $res = $this->User->save($this->request->data,true, array('firstname','lastname','username','email','password','token_expired','token','role','regdate','lastactiv'));
        if (!$res) {
            throw new Exception("Unable to save registered user!");
        }
    }
    
    protected function emailNewUserActivateAccount() {
        App::uses('CakeEmail', 'Network/Email');
        $sitename = Configure::read('Creativos.sitename');
        $from    = Configure::read('Creativos.email.from');
        $subject = Configure::read('Creativos.email.subjects.register');
        
        $email = new CakeEmail();
        $email->viewVars($this->request->data);
        $email->from($from);
        $email->to(array(
            $this->request->data['User']['email'] => $this->request->data['User']['firstname']." ".$this->request->data['User']['lastname']
        ));
        $email->subject($sitename.' - '.$subject);
        $email->template('register');
        $email->emailFormat('html');
        $res = $email->send();
        if (!$res) {
            throw new Exception("Unable to send register email!");
        }
    }
    
    public function beforeFilter() {
        parent::beforeFilter();
        Configure::load('Recaptcha.key');
        $this->Auth->allow('*');
    }
    
	public function index() {
        
        if ($this->request->data) {
            $this->User->set($this->request->data);
            if ($this->User->validates()) {
                
                $this->registerNewUserRequest();
                $this->emailNewUserActivateAccount();
                
                $this->redirect('checkemail');
            }
        }
	}
    
    public function token($id = null) {
        if (empty($id)) {
            $this->redirect('index');
        } else {
            $user = $this->User->find('first', array(
                'conditions' => array(
                    'User.token' => $id
                )
            ));
            if ($user) {
                //The user exists, activate and invalidate token
                $this->User->updateAll(
                    array(
                        'User.token' => null,
                        'User.token_expired' => null,
                        'User.status' => "'ACTIVE'",
                        'User.lastactiv' => 'NOW()'
                    ),
                    array('User.id' => $user['User']['id'])
                );
                unset($user['User']['password']);
                if ($this->Auth->login($user['User'])) {
                    $this->redirect('active');
                } else {
                    $this->Session->setFlash(__('Usuario y/o contraseña inválida'), 'default', array(), 'auth');
                }
            } else {
                //Token doesn't exist, redirect to an error page.
                //$this->render('tokenerror');
                $this->redirect('tokenerror');
            }
        }
    }
    
    public function tokenerror() {}
    public function active() {}

	public function checkemail() {
		
	}
}
?>